package com.winexpress.product;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceRef;

@WebServlet(name = "SearchManagement", urlPatterns = {"/searchManagement/*"})
public class SearchManagement extends HttpServlet {

    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/WineXpress-war/SearchManagementWS.wsdl")
    private SearchManagementWS_Service service;

    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/WineXpress-war/ProductManagementWS.wsdl")
    private ProductManagementWS_Service service1;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        try {
            RequestDispatcher dispatcher;
            ServletContext servletContext = getServletContext();
            HttpSession session = request.getSession(true);
            String page = request.getPathInfo().substring(1);

            SearchManagementWS searchPort = service.getSearchManagementWSPort();
            ProductManagementWS port = service1.getProductManagementWSPort();

            List<Wine> wineList = null;
            List<Category> categoryList = null;

            //customer search
            if (page.equals("shop")) {
                //Get Number of Items in Cart
                int count = 0;
                if (session.getAttribute("items") == null) {
                    int i = 0;
                    request.setAttribute("itemsnum", i);
                } else {
                    String items = (String) session.getAttribute("items");
                    String[] array = items.split("\\;");
                    for (int i = 1; i < array.length; i = i + 2) {
                        count = count + Integer.parseInt(array[i]);
                    }
                    request.setAttribute("itemsnum", count);
//                    session.setAttribute("itemsnum", count);
                }
                //End Number of Items in Cart

                wineList = port.listWinesForShop();
                inital(session, port, wineList);

                String searchBy = request.getParameter("seach");

                if (searchBy != null) {
                    String key = request.getParameter("key");
                    switch (searchBy) {
                        case "searchByWineName":
                            wineList = searchPort.searchByWineName(key);
                            break;
                        case "searcyByCategory":
                            wineList = searchPort.searchByCatgory(key);
                            break;
                        case "searchByCountry":
                            wineList = searchPort.searchByCountry(key);
                            break;
                        case "searchByRegion":
                            wineList = searchPort.searchByRegion(key);
                            break;
                        case "searchByVarietal":
                            wineList = searchPort.searchByVarietal(key);
                            break;
                        case "searchByVintage":
                            wineList = searchPort.searchByVintage(key);
                            break;
                    }

                    for (Object o : wineList) {
                        Wine w = (Wine) o;
                        if (!w.isActive) {
                            wineList.remove(w);
                        }
                    }
                }
                session.setAttribute("wineList", wineList);
            }

            //admin search
            if ("manageWines".equals(page)) {

                String searchBy = request.getParameter("search");

                if (searchBy != null) {
                    String key = request.getParameter("key");

                    switch (searchBy) {
                        case "searchCategory":
                            categoryList = searchPort.searchCatgory(key);
                            request.setAttribute("categoryList", categoryList);
                            request.setAttribute("isSearchCatgory", true);
                        case "searchByWineName":
                            wineList = searchPort.searchByWineName(key);
                            break;
                        case "searcyByCategory":
                            wineList = searchPort.searchByCatgory(key);
                            break;
                        case "searchByCountry":
                            wineList = searchPort.searchByCountry(key);
                            break;
                        case "searchByRegion":
                            wineList = searchPort.searchByRegion(key);
                            break;
                        case "searchByVarietal":
                            wineList = searchPort.searchByVarietal(key);
                            break;
                        case "searchByVintage":
                            wineList = searchPort.searchByVintage(key);
                            break;
                    }
                }
                
                session.setAttribute("wineCategoryList", getCategoryList(wineList));
                session.setAttribute("winesList", wineList);
            }

            dispatcher = servletContext.getNamedDispatcher(page);
            if (dispatcher == null) {
                dispatcher = servletContext.getNamedDispatcher("Error");
            }
            dispatcher.forward(request, response);
        } catch (Exception ex) {
            log("Exception in SearchManagement servlet");
            log(ex.getMessage());
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void inital(HttpSession session, ProductManagementWS port, List<Wine> list) {

        List<Category> categoryList = port.listCategory();
        List<String> category = new ArrayList<>();
        for (Object o : categoryList) {
            Category c = (Category) o;
            category.add(c.getName());
        }
        session.setAttribute("category", category);

        List<String> country = new ArrayList<>();
        for (Object o : list) {
            Wine w = (Wine) o;
            String st = w.getCountry();
            if (!country.contains(st)) {
                country.add(st);
            }
        }
        session.setAttribute("country", country);

        List<String> region = new ArrayList<>();
        for (Object o : list) {
            Wine w = (Wine) o;
            String st = w.getRegion();
            if (!region.contains(st)) {
                region.add(st);
            }
        }
        session.setAttribute("region", region);

        List<String> varietal = new ArrayList<>();
        for (Object o : list) {
            Wine w = (Wine) o;
            String st = w.getVarietal();
            if (!varietal.contains(st)) {
                varietal.add(st);
            }
        }
        session.setAttribute("varietal", varietal);

        List<String> vintage = new ArrayList<>();
        for (Object o : list) {
            Wine w = (Wine) o;
            String st = w.getVintage();
            if (!vintage.contains(st)) {
                vintage.add(st);
            }
        }
        Collections.sort(vintage);
        session.setAttribute("vintage", vintage);
    }

    private List<Category> getCategoryList(List<Wine> list) {
        ProductManagementWS port = service1.getProductManagementWSPort();
        List<Category> categoryList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Wine w = (Wine) list.get(i);
            Category c = port.findCategory(w.getId().toString());
            categoryList.add(c);
        }
        return categoryList;
    }
}
